//
//  AlbumOfListViewController.m
//  SuperRadio
//
//  Created by Damon on 14/12/17.
//  Copyright (c) 2014年 三个臭皮匠. All rights reserved.
//

#import "AlbumOfListViewController.h"
#import "AlbumDetailsViewController.h"
#import "NetHandler.h"
#import "AlbumListCell.h"
#import "AlbumOfList.h"
#import "ClassifyOfList.h"
#import "Categories.h"

#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+Extension.h"

@interface AlbumOfListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic, retain)UITableView *tableView;

@property(nonatomic, retain)NSMutableArray *arr;

@property(nonatomic, retain)UISegmentedControl *secmentC;

@property(nonatomic, retain)NSMutableArray *hotArr;

@property(nonatomic, retain)NSMutableArray *recentArr;
@property(nonatomic, retain)NSMutableArray *ClassicArr;

// 屏幕的高
@property (nonatomic, assign) CGFloat height;
// 屏幕的宽
@property (nonatomic, assign) CGFloat width;

@property(nonatomic, retain) UIView *myView;

@end

@implementation AlbumOfListViewController


- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
        [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
        //进入刷新状态(一进入程序就下拉刷新)
        [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self.view addSubview:self.myView];
    //1. 在这调用请求网络数据方法（刷新数据）
    
    if (self.secmentC.selectedSegmentIndex == 0) {
        
        [self.hotArr removeAllObjects];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=hot&device=iPhone&page=1&per_page=30&status=0&tag_name=%@", self.categories.name, self.classifyOflist.tname];
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *AlbumListArr = [resultDic objectForKey:@"list"];
            self.hotArr = [NSMutableArray array];
            for (NSMutableDictionary *AlbumDic in AlbumListArr) {
                AlbumOfList *list = [[AlbumOfList alloc]initWithDictionary:AlbumDic];
                [self.hotArr addObject:list];
                [list release];
                
            }
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.hotArr];

            //刷新数据
            [self.tableView reloadData];
            
            
        }];

        
        
        
    } else if (self.secmentC.selectedSegmentIndex == 1) {
        
        [self.recentArr removeAllObjects];
        
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=recent&device=iPhone&page=1&per_page=30&status=0&tag_name=%@", self.categories.name, self.classifyOflist.tname];
        
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *AlbumListArr = [resultDic objectForKey:@"list"];
            self.recentArr = [NSMutableArray array];
            for (NSMutableDictionary *AlbumDic in AlbumListArr) {
                AlbumOfList *list = [[AlbumOfList alloc]initWithDictionary:AlbumDic];
                [self.recentArr addObject:list];
                [list release];
                
            }
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.recentArr];
            //刷新数据
            [self.tableView reloadData];
            
        }];

        
    } else {
        
        [self.ClassicArr removeAllObjects];
        
        NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=classic&device=iPhone&page=1&per_page=30&status=0&tag_name=%@", self.categories.name, self.classifyOflist.tname];
        
        [NetHandler getDataWithURL:str completion:^(NSData *data) {
            
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *AlbumListArr = [resultDic objectForKey:@"list"];
            self.ClassicArr = [NSMutableArray array];
            for (NSMutableDictionary *AlbumDic in AlbumListArr) {
                AlbumOfList *list = [[AlbumOfList alloc]initWithDictionary:AlbumDic];
                [self.ClassicArr addObject:list];
                [list release];
                
            }
            [self.arr removeAllObjects];
            [self.arr addObjectsFromArray:self.ClassicArr];
            //刷新数据
           // [self.tableView reloadData];
            
        }];

        
    }
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        //[self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
        [self.myView removeFromSuperview];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    
    
    
    
    
    
    
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSMutableArray array];
        self.width = [UIScreen mainScreen].bounds.size.width;
        self.height = [UIScreen mainScreen].bounds.size.height;
    }
    return self;
}


#pragma mark 获取最火数据
- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=hot&device=iPhone&page=1&per_page=30&status=0&tag_name=%@", self.categories.name, self.classifyOflist.tname];
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *AlbumListArr = [resultDic objectForKey:@"list"];
        self.hotArr = [NSMutableArray array];
        for (NSMutableDictionary *AlbumDic in AlbumListArr) {
            AlbumOfList *list = [[AlbumOfList alloc]initWithDictionary:AlbumDic];
            [self.hotArr addObject:list];
            [list release];
            
        }
        //[self.arr addObjectsFromArray:self.hotArr];
        
        //刷新数据
        //[self.tableView reloadData];
        
        
    }];
    
}

//- (void)viewDidDisappear:(BOOL)animated
//{
//    [super viewDidDisappear:animated];
//    
//   NSLog(@"%@", NSStringFromUIEdgeInsets(self.tableView.contentInset));
//
//    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
//
//}


#pragma mark 获取最近数据
- (void)handleRecentData
{
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=recent&device=iPhone&page=1&per_page=30&status=0&tag_name=%@", self.categories.name, self.classifyOflist.tname];
    
    
    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *AlbumListArr = [resultDic objectForKey:@"list"];
        self.recentArr = [NSMutableArray array];
        for (NSMutableDictionary *AlbumDic in AlbumListArr) {
            AlbumOfList *list = [[AlbumOfList alloc]initWithDictionary:AlbumDic];
            [self.recentArr addObject:list];
            [list release];
            
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.recentArr];
        //刷新数据
        [self.tableView reloadData];
        
    }];
}
#pragma mark 获取经典数据
- (void)handleClassicData
{
    
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=classic&device=iPhone&page=1&per_page=30&status=0&tag_name=%@", self.categories.name, self.classifyOflist.tname];

    [NetHandler getDataWithURL:str completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *AlbumListArr = [resultDic objectForKey:@"list"];
        self.ClassicArr = [NSMutableArray array];
        for (NSMutableDictionary *AlbumDic in AlbumListArr) {
            AlbumOfList *list = [[AlbumOfList alloc]initWithDictionary:AlbumDic];
            [self.ClassicArr addObject:list];
            [list release];
            
        }
        [self.arr removeAllObjects];
        [self.arr addObjectsFromArray:self.ClassicArr];
        //刷新数据
        [self.tableView reloadData];
        
    }];
}

#pragma mark 视图载入
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self handleData];
    
    self.myView = [[UIView alloc] initWithFrame:self.view.frame];
    self.myView.userInteractionEnabled = YES;
    self.myView.backgroundColor = [UIColor clearColor];
    
    self.view.backgroundColor = [UIColor blueColor];
    self.navigationItem.title = self.classifyOflist.tname;
//    // 导航栏右侧按钮
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(clicked:)];
#pragma mark TableView的初始化
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0,[UIScreen mainScreen].bounds.size.width , self.height) style:UITableViewStylePlain];
    self.tableView.rowHeight = 120;
    
    UIImageView *imageViewBackground = [[UIImageView alloc] initWithFrame:self.view.frame];
    [imageViewBackground setImage:[UIImage imageNamed:@"1.jpg"]];
    imageViewBackground.alpha = 0.5;
    self.tableView.backgroundView = imageViewBackground;
   
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.sectionHeaderHeight = 40;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
#pragma mark segement的初始化
    
    self.secmentC = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"最火",@"最近更新",@"经典", nil]];
    self.secmentC.selectedSegmentIndex = 1;
    self.secmentC.frame = CGRectMake(0, 5, self.view.frame.size.width, 30);
    [self.secmentC addTarget:self action:@selector(change:) forControlEvents:UIControlEventValueChanged];
    //[self.view addSubview:self.secmentC];
    [_secmentC release];

    [self setupRefresh];
    // Do any additional setup after loading the view.
}

#pragma mark segement的点击事件
- (void)change:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        [self.arr removeAllObjects];
        
        if (self.hotArr.count != 0) {
            [self.arr addObjectsFromArray:self.hotArr];
            [self.tableView reloadData];
        } else {
            
            [self handleData];
        }
        
        
    } else if (segment.selectedSegmentIndex == 1){
        [self.arr removeAllObjects];
        
        if (self.recentArr.count != 0) {
            [self.arr addObjectsFromArray:self.recentArr];
            [self.tableView reloadData];
        } else {
            
            [self handleRecentData];
        }
        
        
    }else if(segment.selectedSegmentIndex == 2){
        
        [self.arr removeAllObjects];
        
        if (self.ClassicArr.count != 0) {
            [self.arr addObjectsFromArray:self.ClassicArr];
            [self.tableView reloadData];
        } else {
            
            [self handleClassicData];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AlbumOfList * albumOflist = [self.arr objectAtIndex:indexPath.row];
    AlbumDetailsViewController *albumDetailsVC = [[AlbumDetailsViewController alloc] init];
    albumDetailsVC.albumOfList = albumOflist;
    [self.navigationController pushViewController:albumDetailsVC animated:YES];
    [albumDetailsVC release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"sdaf";
    
}

// 设置segment在section的header上
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
    // Create header view and add label as a subview
    UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, tableView.bounds.size.height)] autorelease];
    [sectionView setBackgroundColor:[UIColor clearColor]];
    // sectionView.userInteractionEnabled = YES;
    [sectionView addSubview:self.secmentC];
    
    return sectionView;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str  = @"reuse";
    AlbumListCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[AlbumListCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str]autorelease];
       // cell.alpha = 0.2;
        cell.backgroundColor = [UIColor clearColor];
    }
    AlbumOfList *lia = [self.arr objectAtIndex:indexPath.row];
    cell.albumOfList = lia;
    
    return cell;
}

#pragma mark 导航栏右侧按钮点击
- (void)clicked:(UIBarButtonItem *)barButton
{
    AlbumDetailsViewController *albumDetailsVC = [[AlbumDetailsViewController alloc] init];
    [self.navigationController pushViewController:albumDetailsVC animated:YES];
    [albumDetailsVC release];
    
}

#pragma mark 释放
- (void)dealloc
{
    [_arr release];
   // [_tableView release];
    [_ClassicArr release];
    [_classifyOflist release];
    [_hotArr release];
    [_secmentC release];
    [_categories release];
    
    [super dealloc];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
